﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using MapControl;
using MapControl.Misc;
using MITI;

namespace GPSMap
{
    public partial class frmGPSData : Form
    {
        public frmGPSTracking formMain;
        //private DataTable GeneralClass.dbTestGPS;

        public bool isStartTestGPSData = false;
        //private GPSPoint GeneralClass.currGPSData;
        //private Dictionary<string, List<GPSPoint>> dataList;

        //COM Port
        //public bool Connected = false;
        //public ComPort objPort;

        //public bool isShowGPSData = true; //hiển thị tọa độ GPS trên bản đồ hay không

        public frmGPSData(frmGPSTracking frm, ComPort comPort)
        {
            formMain = frm;
            InitializeComponent();
            //RefreshDB();
            formMain.mapControl.AxMap_MouseDownEvent += new AxMapXLib.CMapXEvents_MouseDownEventHandler(AxMap_MouseDownEvent);
            dataGridViewGPSData.DataSource = GeneralClass.dbTestGPS;
            InitDataGridView();

            //objPort = comPort;
            GeneralClass.objPort.comPort_DataReceivedEvent2 += new SerialDataReceivedEventHandler(comPort_DataReceived2);
        }

        private void frmTestGPSData_Load(object sender, EventArgs e)
        {
            //checkBoxFilter_CheckedChanged(null,null);
            if (GeneralClass.dbTestGPS.Rows.Count > 0)
                labelCount.Text = GeneralClass.dbTestGPS.Rows.Count.ToString();
        }

        //#region COM Port

        /// <summary>
        /// 
        /// </summary>
        /// <param name="text"></param>
        delegate void SetTextCallback(int count);
        private void SetText(int count)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.dataGridViewGPSData.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { count });
            }
            else
            {
                labelCount.Text = count.ToString();// dataGridViewGPSData.Rows.Count.ToString();
                if (count > 0)
                {
                    try
                    {
                        dataGridViewGPSData.CurrentCell = dataGridViewGPSData.Rows[count - 1].Cells[0];
                        dataGridViewGPSData.Rows[count - 1].Selected = true;
                    }
                    catch
                    {
                        dataGridViewGPSData.DataSource = GeneralClass.dbTestGPS;
                    }
                        
                }
            }
        }

        public void comPort_DataReceived2(object sender, SerialDataReceivedEventArgs e)
        {
            //foreach (string text in GeneralClass.objPort.ListMessages)
            //{
                //Nếu Msg không phải "NAME-ACK" thì mới reply NAME-ACK
                //if (!text.Contains(GeneralClass.objPort.ACK_MSG))
                //{
                    //Hiển thị kết quả lên datagridview
                    //Để tránh lỗi cross-thread dùng hàm delegate SetText
                    SetText(GeneralClass.dbTestGPS.Rows.Count);
                //}
            //}
        }

        //#endregion

        //private void RefreshDB()
        //{
        //    //GeneralClass.currGPSData = null;
        //    string sql = "select * from gpsdata";
        //    if (checkBoxFilter.Checked)
        //    {
        //        sql += string.Format(" where name = '{0}'", comboBoxPlane.SelectedValue);
        //        sql += string.Format("and (localtime >= '{0}' and localtime <= '{1}')",
        //                             dateTimePickerStart.Value.ToString("yyyy-MM-dd hh:mm:ss"),
        //                             dateTimePickerEnd.Value.ToString("yyyy-MM-dd hh:mm:ss"));
        //    }

        //    GeneralClass.dbTestGPS = BaseDBCe.ExecSql_DataSet(sql).Tables[0];
        //    dataGridViewGPSData.DataSource = GeneralClass.dbTestGPS;
        //    ////Với mỗi máy bay ta sẽ lưu các tọa độ của nó
        //    //dataList = new Dictionary<string, List<GPSPoint>>();
        //    //for (int i = 0; i < GeneralClass.dbTestGPS.Rows.Count; i++)
        //    //{
        //    //    GPSPoint gpsdata = GetGPSData(GeneralClass.dbTestGPS.Rows[i]);
        //    //    //Nếu data list chứa máy bay rồi
        //    //    if (dataList.ContainsKey(gpsdata.Name))
        //    //        dataList[gpsdata.Name].Add(gpsdata);
        //    //    else //nếu chưa khởi tạo thông tin của máy bay
        //    //    {
        //    //        dataList.Add(gpsdata.Name, new List<GPSPoint>());
        //    //        dataList[gpsdata.Name].Add(gpsdata);
        //    //    }
        //    //}
        //    formMain.mapControl.Map.Refresh();
        //}

        private void InitDataGridView()
        {
            //formMain.mapControl.AxMap_MouseDownEvent += new AxMapXLib.CMapXEvents_MouseDownEventHandler(AxMap_MouseDownEvent);
            //formMain.mapControl.AxMap_DrawUserLayer += new AxMapXLib.CMapXEvents_DrawUserLayerEventHandler(AxMap_DrawUserLayer);

            dataGridViewGPSData.Columns[0].HeaderText = "Thời gian";
            dataGridViewGPSData.Columns[1].HeaderText = "Tên";
            dataGridViewGPSData.Columns[2].HeaderText = "Vĩ độ";
            dataGridViewGPSData.Columns[3].HeaderText = "Kinh độ";
            dataGridViewGPSData.Columns[4].HeaderText = "Độ cao";
            dataGridViewGPSData.Columns[5].HeaderText = "Tốc độ";
            dataGridViewGPSData.Columns[6].HeaderText = "Hướng";

            dataGridViewGPSData.Columns[0].Width = 115;
            dataGridViewGPSData.Columns[0].DefaultCellStyle.Format = "dd/MM/yyyy HH:mm:ss";
            dataGridViewGPSData.Columns[1].Width = 35;
            dataGridViewGPSData.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridViewGPSData.Columns[2].Width = 55;
            dataGridViewGPSData.Columns[2].DefaultCellStyle.Format = "#.00000";
            dataGridViewGPSData.Columns[3].Width = 60;
            dataGridViewGPSData.Columns[3].DefaultCellStyle.Format = "#.00000";
            dataGridViewGPSData.Columns[4].Width = 48;
            dataGridViewGPSData.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dataGridViewGPSData.Columns[5].Width = 49;
            dataGridViewGPSData.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dataGridViewGPSData.Columns[6].Width = 41;
            dataGridViewGPSData.Columns[6].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;


        }

        //private void btnTest_Click(object sender, EventArgs e)
        //{
        //    isStartTestGPSData = !isStartTestGPSData;
        //    if (isStartTestGPSData)
        //    {
        //        btnTest.Text = "Dừng thêm dữ liệu";
        //    }
        //    else
        //    {
        //        btnTest.Text = "Bắt đầu thêm dữ liệu";
        //        RefreshDB();
        //    }
        //}

        public void AxMap_MouseDownEvent(object sender, AxMapXLib.CMapXEvents_MouseDownEvent e)
        {
            PointF pScreen = new PointF(e.x, e.y);
            Graphics g = formMain.mapControl.Map.CreateGraphics();

            if (e.button == 1)
            {
                //for (int i = 0; i < GeneralClass.dbTestGPS.Rows.Count; i++)
                //{
                //    GPSPoint objGPS = GetGPSData(GeneralClass.dbTestGPS.Rows[i]);
                //    //Nếu click trúng vào vị trí GPS thì hiển thị form
                //    if (objGPS.HitTest(pScreen) == 0 &&
                //        formMain.mapControl.Map.CurrentTool == MapXLib.ToolConstants.miArrowTool)
                //    {
                //        if (dataGridViewGPSData != null)
                //            dataGridViewGPSData.Rows[i].Cells["name"].Selected = true;
                //    }
                //}

            }
            g.Dispose();
        }

        ///// <summary>
        ///// Lưu vào CSDL
        ///// </summary>
        //public void SaveIntoDataBase()
        //{
        //    //Lưu vào CSDL
        //    string sql = string.Format("insert into gpsdata values ('{0}','{1}',{2},{3},{4},{5},{6})", GeneralClass.currGPSData.LocalTime, GeneralClass.currGPSData.Name, GeneralClass.currGPSData.LatGPS, GeneralClass.currGPSData.LonGPS, GeneralClass.currGPSData.Alt, GeneralClass.currGPSData.Speed, GeneralClass.currGPSData.Angle);
        //    BaseDBCe.ExecSql_NoneQuery(sql);
        //}

        //public GPSPoint GetGPSData(DataRow row)
        //{
        //    DateTime localTime = DateTime.Parse(row["localtime"].ToString());
        //    string name = row["name"].ToString();
        //    double lon = double.Parse(row["lon"].ToString());
        //    double lat = double.Parse(row["lat"].ToString());
        //    double alt = double.Parse(row["alt"].ToString());
        //    double speed = double.Parse(row["speed"].ToString());
        //    double angle = double.Parse(row["angle"].ToString());
        //    GPSPoint obj = new GPSPoint(formMain.mapControl.Map, name, localTime, lon, lat, alt, speed, angle);

        //    return obj;
        //}

        //public void AxMap_DrawUserLayer(object sender, AxMapXLib.CMapXEvents_DrawUserLayerEvent e)
        //{
        //    if (isShowGPSData)
        //    {
        //        if (formMain.mapControl.Map.Zoom < 10000)
        //        {
        //            Graphics g = Graphics.FromHdc(new IntPtr(e.hOutputDC));
        //            //Với mỗi máy bay khác nhau ta nối đường vẽ cho các máy bay đó
        //            //foreach (KeyValuePair<string, List<GPSPoint>> data in dataList)
        //            //{
        //            //    Color col = Color.Blue;
        //            //    List<PointF> pointList = new List<PointF>();
        //            //    foreach (GPSPoint gpsPoint in data.Value)
        //            //    {
        //            //        pointList.Add(gpsPoint.CenterPoint);
        //            //        if (gpsPoint.LocalTime != GeneralClass.currGPSData.LocalTime)
        //            //            gpsPoint.Draw(g, col);
        //            //    }
        //            //    //Nếu thể hiện lộ trình
        //            //    Pen pen = new Pen(Color.Red, 2);
        //            //    if (checkBoxShowRoutes.Checked)
        //            //        g.DrawLines(pen, pointList.ToArray());
        //            //    pen.Dispose();
        //            //}

        //            List<PointF> pointList = new List<PointF>();
        //            foreach (DataRow dr in GeneralClass.dbTestGPS.Rows)
        //            {
        //                GPSPoint gpsPoint = GetGPSData(dr);
        //                pointList.Add(gpsPoint.CenterPoint);
        //                //Bỏ qua nếu là tọa độ hiện hành (tọa độ đang chọn hoặc tọa độ mới nhất)
        //                if (gpsPoint.LocalTime != GeneralClass.currGPSData.LocalTime)
        //                    gpsPoint.Draw(g);
        //            }

        //            //Nếu thể hiện lộ trình
        //            Pen pen = new Pen(Color.Red, 2);
        //            if (checkBoxShowRoutes.Checked)
        //                g.DrawLines(pen, pointList.ToArray());
        //            pen.Dispose();

        //            //Hiển thị máy bay đang chọn
        //            if (GeneralClass.currGPSData != null)
        //            {
        //                GeneralClass.currGPSData.DrawCurrPoint(g);
        //            }
        //            g.Dispose();
        //        }
        //    }
        //}

        
        //private Color GetRandomColor()
        //{
        //    Random rnd = new Random();
        //    PropertyInfo[] colorProperties = typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.Public);
        //    Color colorName = Color.FromName(colorProperties[rnd.Next(0, colorProperties.Length)].Name);
        //    return colorName;
        //}

        private void frmTestGPSData_FormClosed(object sender, FormClosedEventArgs e)
        {
            t.Enabled = false;
            formMain.mapControl.Refresh();
        }

        //private void checkBoxFilter_CheckedChanged(object sender, EventArgs e)
        //{
        //    comboBoxPlane.Enabled = checkBoxFilter.Checked;
        //    dateTimePickerStart.Enabled = checkBoxFilter.Checked;
        //    dateTimePickerEnd.Enabled = checkBoxFilter.Checked;
        //    btnFilter.Enabled = checkBoxFilter.Checked;
        //    if(checkBoxFilter.Checked)
        //    {
        //        DataSet dsPlane = BaseDBCe.ExecSql_DataSet("select distinct name from gpsdata");
        //        comboBoxPlane.DisplayMember = "name";
        //        comboBoxPlane.ValueMember = "name";
        //        comboBoxPlane.DataSource = dsPlane.Tables[0].DefaultView;

        //        dateTimePickerEnd.Value = DateTime.Now;
        //    }
        //    else
        //    {
        //        RefreshDB();
        //    }
        //}

       

        //private void btnFilter_Click(object sender, EventArgs e)
        //{
        //    //string value = "";
            
        //    //for(int i = 0; i< dataGridViewGPSData.Columns.Count; i++)
        //    //{
        //    //    DataGridViewColumn col = dataGridViewGPSData.Columns[i];
        //    //    value += string.Format(" dataGridViewGPSData.Columns[{0}].Width = {1} ", i.ToString(), col.Width.ToString());
        //    //}
        //    //value += " " + this.Width.ToString();
        //    RefreshDB();
        //}

        
        private void btnReset_Click(object sender, EventArgs e)
        {
            if (GeneralClass.objPort.IsOpen())
            {
                MessageBox.Show("Đóng cổng COM trước mới xóa!");
                return;
            }
            formMain.DeleteAllData();
            labelCount.Text = GeneralClass.dbTestGPS.Rows.Count.ToString();
            dataGridViewGPSData.DataSource = GeneralClass.dbTestGPS;
        }

        private void dataGridViewGPSData_CurrentCellChanged(object sender, EventArgs e)
        {
            //if (GeneralClass.dbTestGPS.Rows.Count > 0)
            //{
            //    //Nếu không phải đang tạo dữ liệu test
            //    if (!isStartTestGPSData)
            //    {
            //        if (dataGridViewGPSData.CurrentRow != null)
            //        {
            //            //GeneralClass.currGPSData = GetGPSData(GeneralClass.dbTestGPS.Rows[dataGridViewGPSData.CurrentCell.RowIndex]);
                        
            //            //GeneralClass.currGPSData.DrawPlaneImage(g);
            //            //formMain.mapControl.Map.ZoomTo(formMain.mapControl.Map.Zoom, GeneralClass.currGPSData.LonGPS, GeneralClass.currGPSData.LatGPS);
            //            //GeneralClass.currGPSData.Draw(g, Color.Red);
            //            //formMain.mapControl.Map.Refresh();
            //        }
            //    }
            //}
        }

        private int indexRow = 0;
        public void OnTimerEvent(object source, EventArgs e)
        {
            BaseGPSPoint gpsdata = new GPSNormalPoint(formMain.mapControl.Map, GeneralClass.dbTestGPS.Rows[indexRow]);
            
                dataGridViewGPSData.CurrentCell = dataGridViewGPSData.Rows[indexRow].Cells[0];
                dataGridViewGPSData.Rows[indexRow].Selected = true;
            char[] data = gpsdata.ConverToByteArray();
            char[] buff = GeneralClass.objPort.SendGPSData(data);
            indexRow++;

            //if (indexRow == 10)
                //t.Enabled = false;

            if (indexRow == GeneralClass.dbTestGPS.Rows.Count-1)
                indexRow = 0;
        }
        private Timer t = new Timer();
        private void btnSendToComPort_Click(object sender, EventArgs e)
        {
            if (dataGridViewGPSData.Rows.Count == 0)
            {
                MessageBox.Show("Không có dữ liệu test để truyền!");
                return;
            }

            if (!GeneralClass.objPort.IsOpen())
            {
                MessageBox.Show("Chưa mở cổng COM");
                return;
            }
            t.Interval = 1000;
            t.Enabled = true;
            t.Tick += new System.EventHandler(OnTimerEvent);
        }

        private void dataGridViewGPSData_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //if (GeneralClass.dbTestGPS.Rows.Count > 0)
            //{
                if (dataGridViewGPSData.CurrentRow != null)
                {
                    //GeneralClass.currGPSData = formMain.GetGPSData(GeneralClass.dbTestGPS.Rows[dataGridViewGPSData.CurrentCell.RowIndex]);
                    //formMain.mapControl.Map.ZoomTo(formMain.mapControl.Map.Zoom, GeneralClass.currGPSData.LonGPS, GeneralClass.currGPSData.LatGPS);

                    BaseGPSPoint objPoint = new GPSNormalPoint(formMain.mapControl.Map, GeneralClass.dbTestGPS.Rows[dataGridViewGPSData.CurrentCell.RowIndex]);
                    formMain.mapControl.Map.ZoomTo(formMain.mapControl.Map.Zoom, objPoint.LonGPS, objPoint.LatGPS);
                    formMain.mapControl.Refresh();
                    
                    Graphics g = formMain.mapControl.Map.CreateGraphics();
                    objPoint.Draw(g, Color.Red);
                }
            //}
        }

        private void btnViewLogs_Click(object sender, EventArgs e)
        {
            string viewfile = "viewlogs.txt";
            File.Copy(GeneralClass.LogsFile,viewfile,true);
            Process.Start("notepad.exe", viewfile);
        }
    }
}